package com.sumer.brain.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sumer.brain.common.model.R;
import com.sumer.brain.common.utils.EasyExcelUtil;
import com.sumer.brain.business.model.entity.School;
import com.sumer.brain.business.model.req.SchoolReq;
import com.sumer.brain.business.service.SchoolService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@RestController
@RequiredArgsConstructor
@Tag(name = "学校管理")
@RequestMapping("/business/school")
public class SchoolController {

    private final SchoolService schoolService;

    @Operation(summary = "分页查询学校列表", description = "分页查询学校列表", tags = "查询")
    @PostMapping("page")
    public R<Page<School>> page(@RequestBody SchoolReq schoolReq) {
        Page<School> page = new Page<>(schoolReq.getPageNum(), schoolReq.getPageSize());
        LambdaQueryWrapper<School> lambdaQueryWrapper = new LambdaQueryWrapper<School>();
        return R.ok(schoolService.page(page, lambdaQueryWrapper));
    }

    @Operation(summary = "查询学校列表", description = "查询学校列表", tags = "查询")
    @GetMapping("list")
    public R<List<School>> list() {
        return R.ok(schoolService.list());
    }

    @Operation(summary = "根据id查询学校信息", description = "根据id查询学校信息", tags = "查询")
    @GetMapping("{id}")
    public R<School> getById(@PathVariable("id") Long id) {
        return R.ok(schoolService.getById(id));
    }

    @Operation(summary = "新增学校", description = "新增学校", tags = "新增")
    @PostMapping()
    public R<Boolean> add(@RequestBody @Validated School sysRole) {
        return R.ok(schoolService.save(sysRole));
    }

    @Operation(summary = "编辑学校", description = "编辑学校", tags = "编辑")
    @PutMapping
    public R<Boolean> edit(@RequestBody School school) {
        return R.ok(schoolService.updateById(school));
    }

    @Operation(summary = "根据ids批量删除学校", description = "根据ids批量删除学校", tags = "删除")
    @DeleteMapping("{ids}")
    public R<Boolean> deleteByIds(@PathVariable("ids") String ids) {
        String[] split = ids.split(",");
        return R.ok(schoolService.removeByIds(Arrays.asList(split)));
    }

    @Operation(summary = "导出" , description = "导出" , tags = "导出")
    @PostMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        List<School> list = schoolService.list();
        EasyExcelUtil.simpleWrite(response, "学校", School.class, list, "学校");
    }
}